﻿package com.pandemicode.framework.smtp.mailer {
	import com.pandemicode.framework.encoding.Base64;
	import flash.utils.ByteArray;
	
	/**
	* @author Mike Lawrence
	*/
	public class EmailAttachment {
		// PNG, JPEG header values
		private static const PNG:Number = 0x89504E47;
		private static const JPEG:Number = 0xFFD8;
		
		private var _fileName:String;
		private var _bytes:ByteArray;
		
		public function get contentType():String {
			this._bytes.position = 0;
			if (this._bytes.readUnsignedInt() == PNG)
				return "image/png";
				
			this._bytes.position = 0;
			if (this._bytes.readUnsignedShort() == JPEG)
				return "image/jpeg";
				
			return "application/octet-stream";
		}
		
		public function EmailAttachment(fileName:String, bytes:ByteArray) {
			this._fileName = fileName;
			this._bytes = bytes;
		}
		
		public function toString():String {
			var base64String:String = Base64.encodeBytes(this._bytes);
			
			var c:String = "Content-Type: "+this.contentType+"; name=\"" + this._fileName + "\"" + Mailer.NEWLINE;
			c += "Content-Disposition: attachment filename=\"" + this._fileName + "\"" + Mailer.NEWLINE;
			c += "Content-Location: " + this._fileName.split(".")[0] + Mailer.NEWLINE;
			c += "Content-ID: <" + this._fileName + ">" + Mailer.NEWLINE;
			c += "Content-Description: "+this._fileName + Mailer.NEWLINE;
			c += "Content-Transfer-Encoding: base64" + Mailer.NEWLINE;
			c += Mailer.NEWLINE;
			c += base64String + Mailer.NEWLINE;
			
			return c;
		}
	}
}
